﻿using SharpShell.Attributes;
using SharpShell.SharpContextMenu;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindiffExtension
{
	[ComVisible(true)]
	[COMServerAssociation(AssociationType.AllFiles)]
	public class Windiff : SharpContextMenu
	{
		protected override bool CanShowMenu()
		{
			return SelectedItemPaths.Count() == 2;
		}

		protected override ContextMenuStrip CreateMenu()
		{
			var menu = new ContextMenuStrip();
			var item = (ToolStripMenuItem)menu.Items.Add("Windiff");
			item.Click += menu_Click;
			return menu;
		}

		void menu_Click(object sender, EventArgs e)
		{
			var file = FindWindiff();
			if(file == null)
				MessageBox.Show("Windiff not found in folders of the environment variable PATH");
			else
			{
				var files = SelectedItemPaths.Reverse().ToArray();
				Process.Start(file.FullName, "\"" + files[0] + "\" \"" + files[1] + "\"");
			}
		}

		private FileInfo FindWindiff()
		{
			var result = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
			foreach(var path in result.Split(';'))
			{
				var file = Path.Combine(path, "windiff.exe");
				if(File.Exists(file))
					return new FileInfo(file);
			}
			return null;
		}
	}
}
